<template>
  <div class="layout">
    <!-- 顶部导航栏 -->
    <header class="header">
      <!-- 顶部工具栏 -->
      <div class="top-bar">
        <div class="container">
          <div class="top-left">

          </div>
          <div class="top-right">
            <!-- 用户已登录时显示用户信息 -->
            <template v-if="isLoggedIn">
              <el-dropdown @command="handleUserCommand" class="user-dropdown">
                <span class="user-info">
                  <el-icon><User /></el-icon>
                  {{ userInfo?.nickname || userInfo?.username || '用户' }}
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                    <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                    <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <!-- 用户未登录时显示登录/注册链接 -->
            <template v-else>
              <span @click="showPolicyDialogHandler" class="clickable">登录</span>
              <span @click="showPolicyDialogHandler" class="clickable">注册</span>
            </template>
            <span>|</span>
            <span>帮助中心</span>
            <span>|</span>
            <span>下载App</span>
            <span>|</span>
            <span>资质证照/协议规则</span>
          </div>
        </div>
      </div>

      <!-- 主导航栏 -->
      <div class="main-nav">
        <div class="container">
          <div class="nav-left">
            <!-- Logo -->
            <router-link to="/" class="logo">
              <img src="/logo.png" alt="小米有品" />
            </router-link>
          </div>

          <div class="nav-center">

          </div>

          <div class="nav-right">
            <!-- 搜索框 -->
            <div class="search-box">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索商品"
                @keyup.enter="handleSearch"
                class="search-input"
              >
                <template #append>
                  <el-button @click="handleSearch" :icon="Search" />
                </template>
              </el-input>
            </div>
            <!-- 购物车 -->
            <router-link to="/cart" class="cart-button">
              <el-badge :value="cartStore.totalCount" :hidden="cartStore.totalCount === 0">
                <el-icon :size="24"><ShoppingCart /></el-icon>
              </el-badge>
            </router-link>
          </div>
        </div>
      </div>

    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <router-view />
    </main>

    <!-- 底部 -->
    <footer class="footer">
      <div class="container">
        <div class="footer-content">
          <div class="footer-section">
            <h4>帮助中心</h4>
            <ul>
              <li><a href="#">账户管理</a></li>
              <li><a href="#">购物指南</a></li>
              <li><a href="#">订单操作</a></li>
            </ul>
          </div>
          <div class="footer-section">
            <h4>服务支持</h4>
            <ul>
              <li><a href="#">售后政策</a></li>
              <li><a href="#">自助服务</a></li>
              <li><a href="#">相关下载</a></li>
            </ul>
          </div>
          <div class="footer-section">
            <h4>线下门店</h4>
            <ul>
              <li><a href="#">小米之家</a></li>
              <li><a href="#">服务网点</a></li>
              <li><a href="#">授权体验店</a></li>
            </ul>
          </div>
          <div class="footer-section">
            <h4>关于小米</h4>
            <ul>
              <li><a href="#">了解小米</a></li>
              <li><a href="#">加入小米</a></li>
              <li><a href="#">联系我们</a></li>
            </ul>
          </div>
        </div>
        <div class="footer-bottom">
          <p>&copy; 2024 小米有品. All rights reserved.</p>
        </div>
      </div>
    </footer>

    <!-- 声明与政策弹框 -->
    <PolicyDialog
      v-model="showPolicyDialog"
      @agree="handlePolicyAgree"
      @disagree="handlePolicyDisagree"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { Search, ShoppingCart, Menu, User, ArrowDown } from '@element-plus/icons-vue'
import { categoryApi, type Category } from '@/api/category'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import PolicyDialog from '@/components/PolicyDialog.vue'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 使用 storeToRefs 确保响应式
const { isLoggedIn, userInfo, token } = storeToRefs(userStore)

// 响应式数据
const searchKeyword = ref('')
const topCategories = ref<Category[]>([])
const showPolicyDialog = ref(false)

// 获取顶级分类
const fetchTopCategories = async () => {
  try {
    const response = await categoryApi.getCategoryTree()
    topCategories.value = response.data || []
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 处理搜索
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push(`/products?keyword=${encodeURIComponent(searchKeyword.value.trim())}`)
  }
}

// 处理用户菜单命令
const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'logout':
      userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/')
      break
  }
}

// 显示政策弹框
const showPolicyDialogHandler = () => {
  showPolicyDialog.value = true
}

// 处理政策同意
const handlePolicyAgree = () => {
  router.push('/auth')
}

// 处理政策不同意
const handlePolicyDisagree = () => {
}

// 组件挂载时初始化
onMounted(() => {
  fetchTopCategories()

  // 简单的状态初始化
  userStore.initFromStorage()

  // 延迟获取用户信息，避免页面刚加载时的冲突
  if (token.value) {
    setTimeout(() => {
      userStore.fetchUserInfo()
      cartStore.fetchCartItems()
    }, 1000)
  }
})

// 监听userInfo变化，确保界面更新
watch(userInfo, (newValue, oldValue) => {
  // 强制更新组件
  if (newValue && !oldValue) {
    // 使用 nextTick 确保 DOM 更新
    nextTick(() => {
      // DOM更新完成
    })
  }
}, { deep: true })
</script>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部工具栏 */
.top-bar {
  background: #333;
  color: white;
  font-size: 12px;
  height: 40px;
  line-height: 40px;
}

.top-bar .container {
  display: flex;
  justify-content: space-between;
}

.top-left span,
.top-right span {
  margin-right: 20px;
  margin-bottom: 20px;
  cursor: pointer;
}

.top-right span.clickable {
  color: white;
  font-weight: 500;
}

.top-right span.clickable:hover {
  color: #f0f0f0;
  text-decoration: underline;
}

.top-left span:hover,
.top-right span:hover {
  color: #ff6700;
}

/* 用户下拉菜单样式 */
.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 5px;
  color: white;
  font-size: 12px;
  padding: 0 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.user-info:hover {
  color: #ff6700;
  background-color: rgba(255, 103, 0, 0.1);
}

/* 主导航栏 */
.main-nav {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: 80px;
}

.main-nav .container {
  display: flex;
  align-items: center;
  height: 100%;
  justify-content: space-between;
}

.nav-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
  text-decoration: none;
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.logo img {
  height: 40px;
}

.logo-text {
  color: #ff6700;
  font-size: 20px;
  font-weight: bold;
}

.nav-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.nav-menu {
  display: flex;
  gap: 40px;
}

.nav-item {
  color: #333;
  text-decoration: none;
  font-size: 16px;
  padding: 10px 0;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
  position: relative;
}

.nav-item:hover,
.nav-item.router-link-active {
  color: #ff6700;
  border-bottom-color: #ff6700;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-box {
  width: 300px;
}

.search-input {
  width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  border: 1px solid #ddd;
  box-shadow: none;
}

.search-input :deep(.el-input__wrapper:hover) {
  border-color: #ff6700;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #ff6700;
  box-shadow: 0 0 0 2px rgba(255, 103, 0, 0.1);
}

.search-input :deep(.el-input-group__append) {
  border-radius: 0 20px 20px 0;
  border-left: none;
  background-color: #ff6700;
}

.search-input :deep(.el-input-group__append .el-button) {
  background-color: transparent;
  border: none;
  color: white;
}

.search-input :deep(.el-input-group__append .el-button:hover) {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.username {
  font-size: 14px;
  color: #333;
}

.cart-button {
  color: #333;
  font-size: 24px;
  text-decoration: none;
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.cart-button:hover {
  color: #ff6700;
  background-color: #f5f5f5;
}

/* 分类导航栏 */
.category-nav {
  background: #f5f5f5;
  height: 50px;
  border-bottom: 1px solid #e0e0e0;
}

.category-nav .container {
  display: flex;
  align-items: center;
  height: 100%;
  gap: 40px;
}

.category-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: #ff6700;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.category-menu {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 20px;
  width: 600px;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.category-item:hover {
  background-color: #f5f5f5;
}

.category-item img {
  width: 24px;
  height: 24px;
}

.quick-nav {
  display: flex;
  gap: 30px;
}

.quick-nav .nav-item {
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s;
}

.quick-nav .nav-item:hover {
  color: #ff6700;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  background: #f5f5f5;
}

/* 底部 */
.footer {
  background: #333;
  color: white;
  padding: 40px 0 20px;
}

.footer-content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 40px;
  margin-bottom: 30px;
}

.footer-section h4 {
  margin-bottom: 15px;
  font-size: 16px;
}

.footer-section ul {
  list-style: none;
}

.footer-section li {
  margin-bottom: 8px;
}

.footer-section a {
  color: #ccc;
  text-decoration: none;
  font-size: 14px;
}

.footer-section a:hover {
  color: white;
}

.footer-bottom {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #555;
  color: #999;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .nav-center .search-box {
    width: 300px;
  }

  .category-menu {
    grid-template-columns: repeat(2, 1fr);
    width: 400px;
  }
}

@media (max-width: 768px) {
  .top-bar {
    display: none;
  }

  .main-nav .container {
    flex-direction: column;
    height: auto;
    padding: 15px 0;
    gap: 15px;
  }

  .nav-left {
    gap: 20px;
  }

  .nav-menu {
    gap: 15px;
  }

  .nav-center .search-box {
    width: 250px;
  }

  .category-nav {
    display: none;
  }

  .footer-content {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }
}
</style>
